package ua.org.extjsbuilder.editors;

import java.util.regex.Pattern;

import org.eclipse.jface.text.rules.ICharacterScanner;
import org.eclipse.jface.text.rules.IRule;
import org.eclipse.jface.text.rules.IToken;
import org.eclipse.jface.text.rules.Token;

public class PatternMatchRule implements IRule{
	private IToken token;
	private Pattern pattern;
	private Pattern allowedCharPattern;
	
	public PatternMatchRule(String pattern, String allowedCharPattern, IToken token){
		this.token = token;
		this.pattern = Pattern.compile(pattern);
		this.allowedCharPattern = Pattern.compile(allowedCharPattern);
	}

	public IToken evaluate(ICharacterScanner scanner) {
		scanner.unread();
		char prev = (char) scanner.read();
		if(allowedCharPattern.matcher(String.valueOf(prev)).matches()){
			return Token.UNDEFINED;
		}
		int nxt = 0;
		int buf = 0;
		StringBuilder wrld = new StringBuilder();
		while((nxt = scanner.read())!=ICharacterScanner.EOF){
			buf++;
			if(!allowedCharPattern.matcher(String.valueOf((char)nxt)).matches()){
				if(pattern.matcher(wrld).matches()){
					scanner.unread();
					return token;
				}
				unreadBuf(buf,scanner);
				return Token.UNDEFINED;
			}
			wrld.append((char)nxt);
		}
		if(pattern.matcher(wrld).matches()){
			return token;
		}
		unreadBuf(buf,scanner);
		return Token.UNDEFINED;
	}

	private void unreadBuf(int buf, ICharacterScanner scanner) {
		while(buf-->0)scanner.unread();
	}

}
